<template>
  <div>
    <ele-split-layout
      width="200px"
      allow-collapse
      :right-style="{ overflow: 'hidden' }"
      :style="{ minHeight: 'calc(100vh - 88px)' }"
    >
      <div
        class="ele-border-split sys-organization-list"
        style="margin-top: 10px; margin-left: 10px"
      >
        <h5 style="background-color: white"
          ><span style="margin-left: 5px">机构列表</span></h5
        >
        <a-divider />
        <a-tree
          :tree-data="(orgData as any)"
          :field-names="{ title: 'name', key: 'id' }"
          :expanded-keys="expandedKeys"
          @select="onTreeSelect"
        />
      </div>
      <template #content>
        <VxeBasicTable ref="TableRef" v-bind="options">
          <template #toolbar_buttons>
            <ToolBtn
              :filter-call="handleOpenFilter"
              :create-call="handleEdit"
              :delete-call="handleDelete"
              :show-export="false"
              :show-import="false"
              :show-delete="false"
            />
          </template>
          <template #action="{ row }">
            <Action
              :record="row"
              @edit="handleEdit"
              @delete="handleDelete"
              @res-set-pwd="resetPsw"
              @auth-role="handleAuthRole"
              @auth-data="handleAuthOrg"
            />
          </template>
        </VxeBasicTable>
      </template>
    </ele-split-layout>
    <!-- 编辑弹窗 -->
    <user-edit v-model:visible="showEdit" :data="current" @done="reload" />
    <!--授权用户角色弹窗-->
    <GrantRoleDrawer
      v-model:visible="showRoleDrawer"
      :data="current"
      @doen="reload"
    />
    <!--授权用户数据弹窗-->
    <GrantOrgDrawer
      v-model:visible="showOrgDrawer"
      :data="current"
      @doen="reload"
    />
    <!-- 导入弹窗 -->
    <user-import v-model:visible="showImport" @done="reload" />
    <TableFilter
      ref="FilterRef"
      @done="reload"
      v-model:visible="ifSHowFilter"
      :filter-cols="Columns"
    />
  </div>
</template>

<script lang="ts" setup>
  import { createVNode, ref, onMounted } from 'vue';
  import { message, Modal } from 'ant-design-vue/es';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { eachTreeData, messageLoading } from 'ele-admin-pro/es';
  import UserEdit from './components/user-edit.vue';
  import GrantRoleDrawer from './components/GrantRoleDrawer.vue';
  import GrantOrgDrawer from './components/GrantOrgDrawer.vue';

  import UserImport from './components/user-import.vue';
  import { pageUsers, removeUser, updateUserPassword } from '@/api/system/user';
  import type { User } from '@/api/system/user/model';
  import { listOrganizations } from '@/api/system/organization';
  import { Organization } from '@/api/system/organization/model';
  import { useConfig } from './config';

  const {
    TableRef,
    FilterRef,
    Columns,
    TableFilter,
    ToolBtn,
    Action,
    options,
    defaultWhere
  } = useConfig(pageUsers);

  // 当前编辑数据
  const current = ref<User | null>(null);

  const orgData = ref<Organization[]>([]);
  const expandedKeys = ref<any[]>([]);

  // 是否显示编辑弹窗
  const showEdit = ref(false);

  const showRoleDrawer = ref(false);

  // 是否显示用户导入弹窗
  const showImport = ref(false);

  const ifSHowFilter = ref(false);

  const showOrgDrawer = ref(false);

  /* 搜索 */
  const reload = () => {
    TableRef?.value?.commitProxy('query');
  };

  /* 打开编辑弹窗 */
  const handleEdit = (row?: User) => {
    current.value = row ?? null;
    showEdit.value = true;
  };

  const handleOpenFilter = () => {
    ifSHowFilter.value = true;
  };

  /* 打开授权用户角色弹窗 */
  const handleAuthRole = (row?: User) => {
    current.value = row ?? null;
    showRoleDrawer.value = true;
  };

  /* 打开授权用户数据弹窗 */
  const handleAuthOrg = (row?: User) => {
    current.value = row ?? null;
    showOrgDrawer.value = true;
  };

  /* 删除单个 */
  const handleDelete = (row: User) => {
    const hide = messageLoading('请求中..', 0);
    removeUser(row.id)
      .then((msg) => {
        hide();
        message.success(msg);
        reload();
      })
      .catch((e) => {
        hide();
        message.error(e.message);
      });
  };

  /* 重置用户密码 */
  const resetPsw = (row: User) => {
    Modal.confirm({
      title: '提示',
      content: '确定要重置此用户的密码吗?',
      icon: createVNode(ExclamationCircleOutlined),
      maskClosable: true,
      onOk: () => {
        const hide = messageLoading('请求中..', 0);
        updateUserPassword(row.id)
          .then((msg) => {
            hide();
            message.success(msg);
          })
          .catch((e) => {
            hide();
            message.error(e.message);
          });
      }
    });
  };

  const onTreeSelect = (keys) => {
    if (keys && keys[0]) {
      defaultWhere.orgId = keys[0];
    }
    reload();
  };
  onMounted(async () => {
    const data = await listOrganizations();
    orgData.value = data;
    eachTreeData(data, (element) => {
      expandedKeys.value.push(element.id);
    });
  });
</script>

<script lang="ts">
  export default {
    name: 'SystemUser'
  };
</script>
